# -*- coding: utf-8 -*-
import os
import sys
import traceback

# 记录每次执行次数
execute_count = 0


# 创建目录:如果不存在
def mkdir(path):
    # 引入模块
    import os
 
    # 去除首位空格
    path=path.strip()
    # 去除尾部 \ 符号
    path=path.rstrip("\\")
 
    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    isExists=os.path.exists(path)
 
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs(path) 
 
        print(path + " created successful!")
        return True
    else:
        # 如果目录存在则不创建，并提示目录已存在
        print(path + " directory is exist!")
        return False
        
# 创建并切换到模块目录
def todir(root,*libname):
    libsDir = root
    for name in libname:
        libsDir +=  os.sep + name
    mkdir(libsDir)
    os.chdir(libsDir)
    print("change dir to "+libsDir)

# 执行命令+打印   
def execute(command):
    print(command)
    os.system(command)


def tryFind(source_path, keyworld) -> bool:
    global execute_count
    execute_count += 1
    if doFind(source_path, keyworld):
        print(f"found {keyworld} in source_path")
        return True
    
    return False
        


def doFind(source_path:str, keyword:str) -> bool:
    function_name = "void updateContainer("
    # function_name = "TaskFragmentContainer newContainer("
    # keyword = "updateSplitContainer"
    # print(f"try to find {keyword} in {source_path}, range is function {function_name}()")
    lines = os.popen(f"cat {source_path}").readlines()

    function_code = ""
    function_in = False
    left_count = 0 # 左花括号
    right_count = 0 # 右花括号
    for i in range(len(lines)):
        line = lines[i]

        if function_in:
            function_code += f"{str(i+1)} "
            function_code += line

            # 记录花括号
            left_count += line.count("{")
            right_count += line.count("}")
            if left_count > 0:
                function_in = left_count != right_count
            continue

        if function_name in line:
            function_code += f"{str(i+1)} "
            function_code += line
            function_in = True
            # 记录花括号
            left_count += line.count("{")
            right_count += line.count("}")
            continue

    # print(f"source code:\n{function_code}")
    return keyword in function_code


def goto_prev(source_dir):
    todir(source_dir)
    execute("git reset --hard HEAD^")


def main():
    
    source_dir = sys.argv[1]
    relative_path = sys.argv[2]
    keyworld = sys.argv[3]

    absolute_path = f"{source_dir}/{relative_path}"

    print(f"source_dir: {source_dir}")
    print(f"relative_path: {relative_path}")
    print(f"absolute_path: {absolute_path}")

    
    while True:
        if os.path.exists(absolute_path):
            ret = tryFind(absolute_path, keyworld)
            if ret:
                break
            else:
                print(f"not found, repeat count: {execute_count}")
                goto_prev(source_dir)
                tryFind(absolute_path, keyworld)
        else:
            print(f"{absolute_path} not found, reset to preview log")
            goto_prev(source_dir)


    return 0

# -------------- main --------------
if __name__ == '__main__':
    sys_ret = 0
    try:
        sys_ret = main()
    except Exception as e:
        print(e)
        traceback.print_exc()
        sys_ret = 1
    finally:
        sys.exit(sys_ret)